package com.metaweb.antTasks;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.charset.Charset;
import java.util.LinkedList;
import java.util.List;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.FileSet;

public class BundleCSSTask extends Task {
	private List<FileSet> _fileSets = new LinkedList<FileSet>();
	private File		  _outputFile;
	private File          _prefixFile;
    private File          _suffixFile;

	public void setOutput(File file) {
		_outputFile = file;
	}
	
	public void setPrefix(File file) {
		_prefixFile = file;
	}
	
    public void setSuffix(File file) {
        _suffixFile = file;
    }
    
	public void addFileSet(FileSet fileSet) {
		_fileSets.add(fileSet);
	}
	
	@Override
	public void execute() throws BuildException {
		if (_outputFile == null) {
			throw new BuildException("No output file specified.");
		}
		
        try {
            OutputStream os = new FileOutputStream(_outputFile);
    		Writer writer = new OutputStreamWriter(os, Charset.forName("UTF-8"));
    		try {
                if (_prefixFile != null) {
                    Utilities.appendUtf8File(os, _prefixFile);
                }
                
    			for (FileSet fileSet : _fileSets) {
    		        File projectDir = fileSet.getDir(getProject());
    	            DirectoryScanner ds = fileSet.getDirectoryScanner(getProject());
    	            
    	            String[] srcFiles = ds.getIncludedFiles();
    	            String[] srcDirs = ds.getIncludedDirectories();
    	            
    	            for (int i = 0; i < srcFiles.length; i++) {
    	            	processFile(new File(projectDir, srcFiles[i]), writer);
    	            }
    	            
    	            for (int i = 0; i < srcDirs.length; i++) {
    	            	processDirectory(new File(projectDir, srcDirs[i]), writer);
    	            }
    			}
                
                if (_suffixFile != null) {
                	Utilities.appendUtf8File(os, _suffixFile);
                }
    		} finally {
    			writer.close();
                os.close();
    		}
        } catch (IOException e) {
            throw new BuildException(e);
        }
	}
	
	protected void processDirectory(File dir, Writer writer) throws IOException {
		File[] files = dir.listFiles();
		for (int i = 0; i < files.length; i++) {
			File file = files[i];
			if (file.isDirectory()) {
				processDirectory(file, writer);
			} else if (file.getName().endsWith(".css")) {
				processFile(file, writer);
			}
		}
	}
	
	protected void processFile(File file, Writer writer) throws IOException {
		if (file.exists()) {
			Utilities.appendCSSFile(writer, file, this._outputFile);
		}
	}
}
